package com.example.waterdispenserm2.mo.copy;

import android.annotation.SuppressLint;
import android.os.Build;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.RequiresApi;

import com.example.waterdispenserm2.R;
import com.example.waterdispenserm2.base.BasicsActivity;
import com.example.waterdispenserm2.databinding.ActivityCopySerialBinding;

//串口+引导码通信
public class CopySerialActivity extends BasicsActivity<ActivityCopySerialBinding> implements
        CopyInductionCookerSlave.OnHostDataReceivedListener,
        CopyInductionCookerSlave.OnLogUpdateListener{

    // 通信实例
    private CopyInductionCookerSlave slave;

    // 数码管段码表（对应文档"显示0发送0x3F"等定义）{insert\_element\_19\_}
    private final char[] segCodeTable = {
            '0', // 0x3F
            '1', // 0x06
            '2', // 0x5B
            '3', // 0x4F
            '4', // 0x66
            '5', // 0x6D
            '6', // 0x7D
            '7', // 0x07
            '8', // 0x7F
            '9', // 0x6F
            'A', // 0x77
            'B', // 0x7C
            'C', // 0x39
            'D', // 0x5E
            'E', // 0x79
            'F'  // 0x71
    };
    @Override
    public void widgetClick(View v) {

    }

    @Override
    public void setListener() {

    }

    @Override
    public void initView() {
        initCommunication();
        initButtonListener();
    }

    @Override
    protected ActivityCopySerialBinding getViewBinding() {
        return ActivityCopySerialBinding.inflate(LayoutInflater.from(this));
    }


    /**
     * 初始化通信
     */
    private void initCommunication() {
        slave = new CopyInductionCookerSlave();
        slave.setOnHostDataReceivedListener(this);
        slave.setOnLogUpdateListener(this);



        if (!TextUtils.isEmpty(binding.etAdd.getText().toString().trim())) {
            // 绑定服务
            binding.btOpen.setOnClickListener(new View.OnClickListener() {
                @SuppressLint("SetTextI18n")
                @Override
                public void onClick(View v) {
                    String path="/dev/ttyS0";
                    if ("0".equals(binding.etAdd.getText().toString().trim())) {
                        path="/dev/ttyS0";
                    } else if ("1".equals(binding.etAdd.getText().toString().trim())) {
                        path="/dev/ttyS1";
                    } else if ("2".equals(binding.etAdd.getText().toString().trim())) {
                        path="/dev/ttyS2";
                    } else if ("3".equals(binding.etAdd.getText().toString().trim())) {
                        path="/dev/ttyS3";
                    } else if ("4".equals(binding.etAdd.getText().toString().trim())) {
                        path="/dev/ttyS4";
                    } else if ("5".equals(binding.etAdd.getText().toString().trim())) {
                        path="/dev/ttyS5";
                    } else if ("6".equals(binding.etAdd.getText().toString().trim())) {
                        path="/dev/ttyS6";
                    } else if ("7".equals(binding.etAdd.getText().toString().trim())) {
                        path="/dev/ttyS7";
                    }
                    // 串口路径和波特率需根据工业平板实际配置修改
                    boolean isInit = slave.init(path, 9600);
                    if (!isInit) {
                        binding.tvUnit.setText("Err");
                    }
                }
            });
        }

        binding.btClase.setOnClickListener(v->{onDestroy();});
        binding.ivMessage.setOnClickListener(v->{finish();});
    }

    /**
     * 初始化按键监听
     */
    private void initButtonListener() {
        binding.btnPower.setOnClickListener(v -> slave.updateKeyStatus((byte) 0x01));
        binding.btnTimer.setOnClickListener(v -> slave.updateKeyStatus((byte) 0x02));
        binding.btnMinus.setOnClickListener(v -> slave.updateKeyStatus((byte) 0x03));
        binding.btnPlus.setOnClickListener(v -> slave.updateKeyStatus((byte) 0x04));
        binding.btnFunction.setOnClickListener(v -> slave.updateKeyStatus((byte) 0x05));
        binding.btnStart.setOnClickListener(v -> slave.updateKeyStatus((byte) 0x06));
    }

    /**
     * 接收主机数据并更新UI
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onHostDataReceived(byte[] displayData) {
        runOnUiThread(() -> {
            // 更新数码管（千位、百位、十位、个位）{insert\_element\_20\_}
            binding.tvThousand.setText(String.valueOf(segCodeTable[displayData[0] & 0x0F]));
            binding.tvHundred.setText(String.valueOf(segCodeTable[displayData[1] & 0x0F]));
            binding.tvTen.setText(String.valueOf(segCodeTable[displayData[2] & 0x0F]));
            binding.tvUnit.setText(String.valueOf(segCodeTable[displayData[3] & 0x0F]));

            // 更新LED灯（bit7-0对应炒菜-煲汤）{insert\_element\_21\_}
            byte ledData = displayData[4];
            binding.ledCook.setBackgroundColor((ledData & 0x80) != 0 ? getColor(R.color.green) : getColor(R.color.gray));
            binding.ledPorridge.setBackgroundColor((ledData & 0x40) != 0 ? getColor(R.color.green) : getColor(R.color.gray));
            binding.ledHotpot.setBackgroundColor((ledData & 0x20) != 0 ? getColor(R.color.green) : getColor(R.color.gray));
            binding.ledHighfire.setBackgroundColor((ledData & 0x10) != 0 ? getColor(R.color.green) : getColor(R.color.gray));
            binding.ledLowfire.setBackgroundColor((ledData & 0x08) != 0 ? getColor(R.color.green) : getColor(R.color.gray));
            binding.ledBoil.setBackgroundColor((ledData & 0x04) != 0 ? getColor(R.color.green) : getColor(R.color.gray));
            binding. ledSteam.setBackgroundColor((ledData & 0x02) != 0 ? getColor(R.color.green) : getColor(R.color.gray));
            binding.ledSoup.setBackgroundColor((ledData & 0x01) != 0 ? getColor(R.color.green) : getColor(R.color.gray));
        });
    }

    /**
     * 更新日志显示
     */
    @Override
    public void onLogUpdated(String log) {
        runOnUiThread(() -> binding.tvLog.append(log));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (slave != null) slave.close();
    }

}